<?php

class TenderController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	public $defaultAction = 'admin';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','namelist'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Tender;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Tender']))
		{
			$model->attributes=$_POST['Tender'];
			$model->tid = Tender::model()->getTenderId();
			//check if the project exists.
			$model->pid = Tender::model()->getProject($_POST['Tender']['pid'],$_POST['Tender']['tendererid']);
			/*$p = Project::model()->findByAttributes(array('projectname'=>$_POST['Tender']['pid']));
			if($p){
				$model->pid = $p->pid;
			}else{
				$newproject = new Project;
				$newproject->projectname = $_POST['Tender']['pid'];
				$newproject->organization = $_POST['Tender']['tendererid'];
				$newproject->save();
				$model->pid = $newproject->pid;
			}*/
			$model->status = 1;
			if($model->save())
				$this->redirect(array('view','id'=>$model->tid));
		}
		$smodel=new Tender('search');
		$smodel->unsetAttributes();  // clear any default values
		if(isset($_GET['Tender'])){
			$smodel->attributes=$_GET['Tender'];
			$smodel->search_project=$_GET['Tender']['search_project'];
			$smodel->search_user=$_GET['Tender']['search_user'];
			$smodel->search_tenderer=$_GET['Tender']['search_tenderer'];
		}
		$tender=Tenderer::model()->findAll();
		$this->render('create',array(
			'model'=>$model,
			'smodel'=>$smodel,
			'tender'=>$tender,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Tender']))
		{
			$model->attributes=$_POST['Tender'];
			$p = Project::model()->findByAttributes(array('projectname'=>$_POST['Tender']['pid']));
			if($p){
				$model->pid = $p->pid;
			}else{
				$newproject = new Project;
				$newproject->projectname = $_POST['Tender']['pid'];
				$newproject->organization = $_POST['Tender']['tendererid'];
				$newproject->save();
				$model->pid = $newproject->pid;
			}
			if($model->save())
				$this->redirect(array('view','id'=>$model->tid));
		}
		$smodel=new Tender('search');
		$smodel->unsetAttributes();  // clear any default values
		if(isset($_GET['Tender'])){
			$smodel->attributes=$_GET['Tender'];
			$smodel->search_project=$_GET['Tender']['search_project'];
			$smodel->search_user=$_GET['Tender']['search_user'];
			$smodel->search_tenderer=$_GET['Tender']['search_tenderer'];
		}
		$tender=Tenderer::model()->findAll();
		$this->render('update',array(
			'model'=>$model,
			'smodel'=>$smodel,
			'tender'=>$tender,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Tender');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	
	/**
	 * Lists all models.
	 */
	public function actionNamelist()
	{
		$model=new Tender;
		if(isset($_GET['tid'])){
			$tid = $_GET['tid'];
			$sql = 'Select b.bid AS bid,s.sname AS sname,c.cname AS cname,c.phone AS phone,c.fax AS fax,c.email AS email From bidder b LEFT JOIN supplies s ON b.sid = s.sid LEFT JOIN contacts c On b.cid = c.cid WHERE b.tid = "'.$tid.'"';
			$result = yii::app()->db->createCommand($sql);
			$query = $result->queryAll(); 
			//if($query)
			$this->render('Namelist',array('model'=>$query,'dumpModel'=>false));
		}
		else
		{
			$this->render('Jump');	
		}
		if(isset($_POST['Namelist']))
		{
			Bidder::model()->deleteAll('tid="'.$_GET['tid'].'"');
			foreach($_POST['Namelist']['company'] as $k => $v)
			{
				//get sid by sname
				$sid = Supplies::model()->getSid($v);
				//get cid by name and tel
				$cid = Contacts::model()->getCid($_POST['Namelist']['contact'][$k],$_POST['Namelist']['phone'][$k],
				$sid,$_POST['Namelist']['fax'][$k],$_POST['Namelist']['email'][$k]);
				//TODO GET BID
				$bidder = new Bidder;
				$bidder->sid = $sid;
				$bidder->cid = $cid;
				$bidder->tid = $_GET['tid'];
				if($bidder->save())
					CVarDumper::dump($bidder,20,true);
					else
					CVarDumper::dump($sid,20,true);;
			}
			//$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}

	}
	
	
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Tender('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Tender'])){
			$model->attributes=$_GET['Tender'];
			$model->search_project=$_GET['Tender']['search_project'];
			$model->search_user=$_GET['Tender']['search_user'];
			$model->search_tenderer=$_GET['Tender']['search_tenderer'];
		}
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Tender::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='tender-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
